#include "httplib.h"
#include "searcher.hpp"
#include "Log.hpp"
#include "Login.hpp"
#include "Register.hpp"
#define WWWROOT "./wwwroot/"
const string input = "./data/output/output.txt";
const string root_path = "./wwwroot";
using namespace httplib;

int main()
{
    search_searcher::Searcher search;
    search.InitSearcher(input); // 确保input已定义

    Server svr;

    svr.set_base_dir(WWWROOT);

    // GET 请求处理
    svr.Get("/s", [&](const Request& req, Response& res) {
        if (!req.has_param("word")) {
            res.status = 400;
            res.set_content("必须要有搜索关键字!", "text/plain; charset=utf-8");
            return;
        }
        std::string word = req.get_param_value("word");
        lg(Info, "用户搜索的: %s", word.c_str());
        std::string json_string;
        search.Search(word, &json_string);
        res.set_content(json_string, "application/json");
    });

    svr.Get("/hotwords", [&](const Request& req, Response& res) {
        std::string json_string;
        search.HotWords(&json_string);
        res.set_content(json_string, "application/json");
    });

    svr.Get("/prefix", [&](const Request& req, Response& res) {
        if (!req.has_param("prefixword")) 
        {
            res.status = 400;
            res.set_content("必须要有要匹配的前缀关键字!", "text/plain; charset=utf-8");
            return;
        }
        std::string prefixword = req.get_param_value("prefixword");
        lg(Info, "用户需要匹配的: %s", prefixword.c_str());
        std::string json_string;
        search.Prefix(prefixword, &json_string);
        res.set_content(json_string, "application/json");
    });

    svr.Post("/login", [&](const Request& req, Response& res) {
        handle_login(req, res);
    });

    svr.Post("/register", [&](const Request& req, Response& res) {
        handle_register(req, res);
    });

    // 监听端口
    svr.listen("0.0.0.0", 8084);

    return 0;
}